package com.skynet.app.api.auth.service.impl;

import com.skynet.app.api.auth.config.SmtpMailProperties;
import com.skynet.app.api.auth.enums.ResultEnum;
import com.skynet.app.api.auth.exception.UserAuthException;
import com.skynet.app.api.auth.service.SmtpMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * @author Skynet
 * @date 2017年11月27日 16:08
 */
@Service
@Slf4j
public class SmtpMailServiceImpl implements SmtpMailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private SmtpMailProperties smtpMailProperties;

    @Override
    @RabbitHandler
    @RabbitListener(queues = "sendEmail")
    public void simpleMailSend(String to) {
        String from = smtpMailProperties.getFrom();
        String subject = smtpMailProperties.getSubject();
        String initPass = smtpMailProperties.getInitPass();
        String textTemplate = smtpMailProperties.getTextTemplate();
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setFrom(from);
        smm.setTo(to);
        smm.setSubject(subject);
        smm.setText(String.format(textTemplate, initPass));

        try {
            log.info("【发送邮件】开始发送邮件，详细信息：from={},to={},subject={}", from, to, subject);
            mailSender.send(smm);
            log.info("【发送邮件】邮件发送成功");
        } catch (MailException e) {
            log.info("【发送邮件】邮件发送失败：", e);
            throw new UserAuthException(ResultEnum.MAIL_SEND_ERROR);
        }
    }
}
